package de.tum.in.eist.im.shared;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Represents a group of Users in EIST_IM environment. A Group has a name, a
 * founder and a List of Users that are in it. It's used twice: the first time
 * for invitng a user, the second time for spreading the acception to all group
 * members.
 * 
 * @author pascal fritzen
 */
public class Group implements Serializable, Iterable<User> {

	private static final long serialVersionUID = 1L;

	private String name;
	private User founder;
	private List<User> groupMember;
	private List<Message> groupMessages;

	@Override
	public int hashCode() {
		return name.hashCode() + groupMember.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof Group)) {
			return false;
		}
		Group other = (Group) obj;
		return this.name.equals(other.name);
	}

	public Group(String name, User founder) {
		this.name = name;
		this.founder = founder;
		this.groupMember = new ArrayList<User>();
		this.groupMessages = new ArrayList<Message>();
	}

	public Group() {
	}

	public String getName() {
		return name;
	}

	public User getFounder() {
		return founder;
	}

	public List<User> getGroupMembers() {
		return groupMember;
	}

	public void addMember(User newUser) {
		groupMember.add(newUser);
	}

	public void removeMember(User oldUser) {
		groupMember.remove(oldUser);
	}

	public Iterator<User> iterator() {
		return groupMember.iterator();
	}

	@SuppressWarnings("deprecation")
	public void addGroupMessage(Message newGroupMessage) {
		Date d = new Date(newGroupMessage.getTimestamp());
		String date = "";
		if (d.getHours() < 10) {
			date += "0" + d.getHours();
		} else {
			date += d.getHours();
		}
		date += ":";
		if (d.getMinutes() < 10) {
			date += "0" + d.getMinutes();
		} else {
			date += d.getMinutes();
		}
		date += ":";
		if (d.getSeconds() < 10) {
			date += "0" + d.getSeconds();
		} else {
			date += d.getSeconds();
		}
		
		FileWriter fw;
		BufferedWriter bw;
		File groupFile = new File(name + ".log");
		
		try {
			fw = new FileWriter(groupFile, true);
			bw = new BufferedWriter(fw);
			bw.write(date + "-"
					+ newGroupMessage.getSender().getUsername() + ":" + 
					newGroupMessage.getText());
			bw.newLine();
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public List<Message> getGroupMessages() {
		return groupMessages;
	}
}
